package com.ldy.demo1;

import java.util.*;
import java.util.concurrent.*;

class Race {
    private Random rand = new Random();

    public int getDistance() {
        return distance;
    }

    private int distance = rand.nextInt(250);
    private CountDownLatch start;
    private CountDownLatch finish;

    private List<String> horses = new ArrayList<String>();

    public Race(String... names) {
        this.horses.addAll(Arrays.asList(names));
    }

    public void run()
            throws InterruptedException {

        System.out.println("----------------------准备马儿入场----------------------");
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch finish = new CountDownLatch(horses.size() + 1);
        final List<String> places =
                Collections.synchronizedList(new ArrayList<String>());

        for (final String h : horses) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println(h +
                                " 来到比赛场地");
                        start.await();

                        int traveled = 0;
                        while (traveled < distance) {
                            // In a 0-2 second period of time....
                            Thread.sleep(rand.nextInt(3) * 1000);

                            // ... a horse travels 0-14 lengths
                            traveled += rand.nextInt(15);
                            System.out.println(h +
                                    " 领先了 " + traveled + "米!");
                        }
                        finish.countDown();
                        System.out.println(h +
                                " 到达终点");
                        places.add(h);
                    } catch (InterruptedException intEx) {
                        System.out.println("比赛意外打断");
                        intEx.printStackTrace();
                    }
                }
            }).start();
        }

        System.out.println("所有参数选手已经入场------------------------");
        start.countDown();

        finish.await();
        System.out.println("下面欢迎我们的优胜者-------------------------");
        System.out.println(places.get(0) + " 拿到金牌");
        System.out.println(places.get(1) + " 拿到银牌");
        System.out.println(places.get(2) + " 拿到铜牌");
    }
}

public class CountDownLatchApp {
    public static void main(String[] args)
            throws InterruptedException, java.io.IOException {
        System.out.println("准备");

        Race r = new Race(
                "张泽坤",
                "赵鹏",
                "卢文康",
                "罗治阳",
                "张胜",
                "李伟斌",
                "刘德咏"
        );

        System.out.println("下面是 " + r.getDistance() + "米赛马的决赛");

        System.out.println("请输入任何键开始这场比赛");
        System.in.read();

        r.run();
    }
}